import {Injectable} from '@angular/core';

@Injectable()
export class WebsocketService {

  private _token;

  constructor() {
  }

  get token() {
    this._token = localStorage.getItem('token');
    return this._token;
  }

  socket(url: string, ...subprotocols: any[]) {
    const subs = [];
    subs.push(this.token, ...subprotocols);
    return new WebSocket(url);
  }
  createMessage(options: { messageType?: string; contentType?: string; data?: any }) {
    return JSON.stringify({
      messageType: options.messageType,
      contentType: options.contentType,
      data: options.data,
      token: this.token
    });
  }

  interval(socket: WebSocket, ms: number, message: any) {
    /**
     * 定时发送消息
     * */
    return setInterval(() => {
      if (socket.readyState === 1) {
        socket.send(this.createMessage(message));
      }
    }, ms);
  }

  send(socket: WebSocket, message: any) {
    if (socket.readyState === 1) {
      socket.send(this.createMessage(message));
    }
  }

  keepAlive(socket: WebSocket, time?: number) {
    if (!time) {
      time = 6000;
    }
    return setInterval(() => {
      socket.send(this.createMessage({
        messageType: 'keep',
        contentType: 'text',
        data: 'ping'
      }));
    }, time);
  }
}
